package com.xx.utils

import sttp.client3.quick.backend

import java.io.{File, PrintWriter}
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
import scala.io.Source
import scala.xml.XML

/**
 *
 * @author tzp
 * @since 2022/2/10
 */
object JiraExporter {
  case class Issue(summary: String, link: String, status: String, created: String, updated: String,
                   reporter: String, assignee: String, description: String, latestComment: String, notUpdated5day: Boolean)

  val formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss Z").withLocale(Locale.UK)


  def main(args: Array[String]): Unit = {
    //val data = fetch()
    val s = Source.fromFile("/Users/tzp/Documents/private/cnm/CodeAccumulate/id-magic/imeigenerator/src/main/scala/com/xx/utils/data.xml")
    val data = s.mkString
    //parse
    val issues = parse(data)
    //out
    outMarkdown(issues)
  }

  def fetch(): String = {
    import sttp.client3._
    val request = basicRequest.header("Authorization", "Basic dGlhbnpoaXBlbmctams6MzYwX3R6cDEyMzQ1Njc4OQ==")
      .get(uri"http://jira.daikuan.qihoo.net/sr/jira.issueviews:searchrequest-xml/15631/SearchRequest-15631.xml")
      .response(asString)
    val response = request.send(backend)
    response.body match {
      case Left(error) => throw new RuntimeException(s"Error when executing request: $error")
      case Right(data) => data
    }
  }

  def parse(data: String): Seq[Issue] = {
    val x = XML.loadString(data)
    (x \ "channel" \ "item").map(issue => {
      val summary = (issue \ "summary").text
      val link = (issue \ "link").text
      val status = (issue \ "status").text
      val created = (issue \ "created").text
      val updated = (issue \ "updated").text
      val reporter = (issue \ "reporter").text
      val assignee = (issue \ "assignee").text
      val description = "<pre>" + (issue \ "description").text.replaceAll("\n", " ") + "</pre>"
      val comments = (issue \ "comments")

      val (latestComment, notUpdated5day) = if (comments == null || comments.length == 0) {
        ("", true)
      } else {
        val lastCommentDate = (comments \\ "comment").last \@ "created"
        val notUpdated5day = LocalDateTime.now().minusDays(5)
          .isAfter(LocalDateTime.parse(lastCommentDate, formatter))
        val latestComment = "<pre>" + (comments \\ "comment").last.text.replaceAll("\n", " ") + "</pre>"
        (latestComment, notUpdated5day)
      }
      Issue(summary, link, status, created, updated, reporter, assignee, description, latestComment, notUpdated5day)
    })
  }

  def outMarkdown(issues: Seq[Issue]): Unit = {
    val header =
      """|任务名|状态|是否超过5天没有进展了|最新进展备注|创建时间|最近更新时间|报告人|经办人|描述|
         |----|----|----|----|----|----|----|----|----|
         |""".stripMargin

    val writer = new PrintWriter(new File("/Users/tzp/Documents/private/cnm/CodeAccumulate/id-magic/imeigenerator/src/main/scala/com/xx/utils/data.xml.md"))
    writer.write(header)

    issues.foreach(x => {
      val redWarning = if (x.notUpdated5day) "<p style=\"background-color: red\">&nbsp;</p>" else "<p style=\"background-color: green\">&nbsp;</p>"
      val line = s"|[${x.summary}](${x.link})|${x.status}|${redWarning}|${x.latestComment}|${x.created}|${x.updated}|${x.reporter}|${x.assignee}|\n"
      writer.write(line)
    })

    writer.flush()
    writer.close()
  }

}
